<?php
class MumberController{
    private $data;
    public function __construct()
    {
        $this -> data  = include './data.php';
    }

    public function login(){
        if(IS_POST){
            //判断验证码
            if($_SESSION['code'] != $_POST['code']){
                success('验证码错误','Index.php?a=Mumber&c=login' );
            }
            //获取用户提交的用户名和密码
            $username = $_POST['username'];
            $password = md5($_POST['password']);
            //循环数据库进行判断
            foreach ($this->data as $u){
                //如果用户名和密码相同
                if ($u['username']==$username && $u['password'] == $password){
                    $_SESSION['username'] = $username;
                    if(isset($_POST['seven'])){
                        setcookie(session_name(),session_id(),time() + 3600 * 24 * 7,'/');
                    }else{
                        setcookie(session_name(),session_id(),0,'/');
                    }
                    success('登陆成功', 'Index.php');
                }
            }
            success('登陆失败','Index.php?a=Mumber&c=login' );
        }

        include './view/login.php';
    }
   /*
    * 注册
    * */
    public function reg(){

        if (IS_POST){
            if($_SESSION['code'] != $_POST['code']){
                success('验证码错误','Index.php?a=Mumber&c=reg' );
            }
			foreach($this->data as $u){
                if($u['username'] == $_POST['username']){
                    success('用户名已存在','Index.php?a=Mumber&c=reg');
                }
            }
          //追加
            $this->data[] = array(
                'username'=>$_POST['username'],
                'password'=>md5($_POST['password']),
            );
            //写入数据库
            file_put_contents('./data.php',"<?php return " . var_export($this->data,true) . "?>");
            success('注册成功','Index.php');
        }
        include './view/reg.php';
    }
    public function out(){
        session_unset();
        session_destroy();
        success('退出成功','Index.php');
    }
    public function showVerify(){
        $code = new Code();
        $code->make();
    }
    public function checkUser(){
        if (isset($_POST['u'])){
            if(!trim($_POST['u'])){
                echo 1;
                exit;
            }
            $username = $_POST['u'];
            foreach ($this->data as $u){
                if($u['username']==$username){
                    echo 1;
                    exit;
                }
            }
            echo 0;
            exit;
        }
        echo 1;exit;
    }
    public function checkCode(){
        if($_POST['code']){
            $code = $_POST['code'];
            if($_SESSION['code']==$code){
                echo 1;
                exit;
            }
            echo 0;
            exit;
        }
    }
}